package agents;

import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import res.Util;
import res.exceptions.InvalidInputGraphException;
import res.graph.Edge;
import res.graph.Graph;
import res.input.GraphReader;

public class TrafficLightAgentCreator {
	
	private final Hashtable<Edge, TrafficLightAgent> agents;
	private final Iterable<Edge> edges;

	public TrafficLightAgentCreator(GraphReader gr) throws InvalidInputGraphException {
		Graph g = gr.readGraph();
		edges = g.getEdges();
		agents = new Hashtable<Edge, TrafficLightAgent>(g.getNumEdges());
		
		createAgents();
	}
	
	private void createAgents() {
		TrafficLightAgent agent = null;
		TrafficLightAgent atmp = null;
		
		for(Edge e : edges) {
			agent = agents.get(e);
			System.out.println(String.format("EDGE: %d-%d", e.getSource().getOrd(), e.getTarget().getOrd()));
			if(agent == null) {
				agent = new TrafficLightAgent(e);
				agents.put(e, agent);
			}

			System.out.print("PARTNERS ");
			for(Edge epart : e.getPartners()) {
				atmp = agents.get(epart);
				System.out.print(String.format("%d-%d ", epart.getSource().getOrd(), epart.getTarget().getOrd()));
				if(atmp == null)
					agent.addPartners(new TrafficLightAgent(epart));
				else
					agent.addPartners(atmp);
			}
			System.out.print("\n\nCOMPETITORS ");
			for(Edge ecomp : e.getCompetitors()) {
				atmp = agents.get(ecomp);
				System.out.print(String.format("%d-%d ", ecomp.getSource().getOrd(), ecomp.getTarget().getOrd()));
				if(atmp == null)
					agent.addCompetitor(new TrafficLightAgent(ecomp));
				else
					agent.addCompetitor(atmp);
			}
			System.out.print("\n\nSUCCESSORS ");
			for(Edge esucc : e.getSuccessors()) {
				atmp = agents.get(esucc);
				System.out.print(String.format("%d-%d ", esucc.getSource().getOrd(), esucc.getTarget().getOrd()));
				if(atmp == null)
					agent.addSuccessor(new TrafficLightAgent(esucc));
				else
					agent.addSuccessor(atmp);
			}
			System.out.println("\n\n");
		}
		
		Util.Simulation.agents = Collections.list(agents.elements());
	}
	
	public void startAgents() {
		for(TrafficLightAgent agent : Util.Simulation.agents) {
			Util.Simulation.scheduler.execute(agent);
		}
			
	}
}
